/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wider.foundation.event;

import com.wider.foundation.concurrency.QueuingAware;
import java.util.ArrayList;
import java.util.Date;
import java.util.Queue;

/**
 * This class in the Event Framework defines a base class of Event.
 *
 * @author William Choi <avextk@gmail.com>
 */
public class Event implements QueuingAware {
    private ArrayList<Queue>    quelist;
    private EventTarget         trgtobj;
    private Object              srceobj;
    private String              eventid;
    private Date                tmestmp;

    public Event(String eventID, EventTarget target, Object source) throws IllegalArgumentException{
        if (null == eventID)
            throw new IllegalArgumentException("An Event MUST be instanciated with a eventID.");

        if (null == target)
            throw new IllegalArgumentException("Target of the Event MUST be specified.");

        if (null == source)
            throw new IllegalArgumentException("Source of the Event MUST be specified.");
        
        eventid = eventID;
        quelist = new ArrayList<Queue>();
        tmestmp = new Date();
        trgtobj = target;
        srceobj = source;
    }

    public String getEventID(){
        return eventid;
    }

    public EventTarget getEventTarget(){
        return trgtobj;
    }

    public Object getEventSource(){
        return srceobj;
    }
    
    @Override
    public String toString(){
        return eventid + "::" + tmestmp + "::" + trgtobj + "::" + srceobj;
    }

    @Override
    public void enterQueue(Queue q) {
        quelist.add(q);
    }

    @Override
    public boolean exitQueue(Queue q) {
        return quelist.remove(q);
    }

    @Override
    public boolean leaveQueue(Queue q) {
        q.remove(this);
        return exitQueue(q);
    }

    @Override
    public boolean isQueued() {
        return (!quelist.isEmpty());
    }

    @Override
    public long leaveAllQueues() {
        long i = 0;

        for (Queue q : quelist){
            leaveQueue(q);
            i++;
        }
        return i;
    }

}
